package com.example.controller;

import com.example.entity.SysUser;
import com.example.service.SysUserService;
import com.example.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.UUID;

/**
 * ----MaxCV工程师---
 *
 * @author wangbiao
 * @date2024/12/2
 * @desc
 */


@RestController
@RequestMapping("/sys/user")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @PostMapping("/login")
    public R login(@RequestBody SysUser sysUser, HttpSession session){

        SysUser user =  sysUserService.login(sysUser);
        System.out.println(user);
        if (user == null){
            return R.fail();
        }
        // 生成token
        String token = UUID.randomUUID().toString();
        HashMap<String,Object> map = new HashMap<>();
        // 创建会话,将查询得到的用户信息保存在会话中,前端登录之后,会发送请求,根据token获取用户信息
        // 此时就可以将会话中的用户信息取出
        session.setAttribute("sysUser",user);
        map.put("token",token);
        return R.ok(map);
    }

    /**
     * 根据token获取用户信息
     */
    @GetMapping("/info")
    public R info(String token ,HttpSession session) {
        if (token == null){
            return R.fail();
        }else {
            SysUser user =(SysUser)session.getAttribute("sysUser");
            return R.ok(user);
        }
    }
    /**
     * 退出功能
     */
    @GetMapping("/logout")
    public R logout(HttpSession session){
        session.invalidate();
        return R.ok();
    }
}
